import { computed, defineComponent, onErrorCaptured, reactive, ref, toRaw } from 'vue';
import { RouterView, RouteRecordRaw, RouteLocationRaw } from 'vue-router';
import { Menu, MenuItem, SubMenu, SubMenuProps, MenuItemProps, Button } from 'ant-design-vue';
import ErrorPage from '../home/error';
import Header from '../header';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons-vue';
import { RouterType, router } from '../../router/index';
import { getParentRouterName, menuData, menuRouter } from '@/domain/dataBoard/hooks/menuInfo';
import { nextTick } from 'process';
import { MenuRouterType } from '@/domain/authority/types/menu';
import { useMenuStore } from '@/domain/dataBoard/hooks/menu';
import { Key } from 'ant-design-vue/lib/table/interface';

export type ClickMenuParam = { item: MenuItemProps; key: string; keyPath: string };

const MenuPage = defineComponent({
  props: {},
  setup(props) {
    /**异常处理 */
    const errorHappened = ref<boolean>(false);
    const errorMessage = ref<string>('');
    /**store  */
    const store = useMenuStore();
    //数据驱动menuinfo
    const menuInfo = computed(() => store.state.menuData);
    const menuDisplay = computed(() => (router.currentRoute.value.name === 'select' || menuInfo.value.length === 0 ? 'none' : 'block'));
    const barInfo = computed(() => getParentRouterName(store.state.menuData));
    const currentRouterInfo = computed(() => menuRouter.filter((node) => node.name === router.currentRoute.value.name));

    const barTitle = computed(() =>
      currentRouterInfo.value.length > 0
        ? barInfo.value.pChName !== ''
          ? barInfo.value.pChName + '-' + currentRouterInfo.value[0].chname
          : currentRouterInfo.value[0].chname
        : ''
    );

    const state = reactive({
      openKeys: [barInfo.value.pName],
      collapsed: false,
      selectedKeys: [router.currentRoute.value.name as Key]
    });
    const click = (path: string) => {
      errorHappened.value = false;
      errorMessage.value = '';
      router.push({ path, replace: false });
    };
    const toggleCollapsed = () => {
      state.collapsed = !state.collapsed;
    };
    const select = ({ item, key, selectedKeys }: any) => {
      state.selectedKeys = selectedKeys;
    };

    const open = ({ item, key, selectedKeys }: any) => {
      state.openKeys = selectedKeys;
    };

    const getMenuItem = (nodelist: RouterType[]) => {
      return (
        <>
          {nodelist.map((val, key) => {
            if (!val.children || val.children.length === 0) {
              return (
                <MenuItem
                  class={'text-sm'}
                  key={val.name as string}
                  // icon={<span class={val.icon} />}
                  onClick={() => {
                    click(`${val.path}`);
                  }}
                >
                  <span class={'ant-menu-item-icon ' + val.icon}></span>
                  <span>{val.chname}</span>
                </MenuItem>
              );
            } else {
              return (
                <SubMenu key={val.name as string} class=" text-sm" title={val.chname} icon={<span class={val.icon} />}>
                  {getMenuItem(val.children)}
                </SubMenu>
              );
            }
          })}
        </>
      );
    };
    const MenuItemList = computed(() =>
      defineComponent({
        setup() {
          return () => getMenuItem(toRaw(menuInfo.value));
        }
      })
    );

    function renderErrorPage() {
      return <ErrorPage message={errorMessage.value} />;
    }
    return () => (
      <div class=" w-full h-full bg-gray-120">
        <Header
          v-slots={{
            default: () => (
              <Button class={'inline-block text-red-400 hover:text-red-400 active:text-red-400 '} type="link" onClick={toggleCollapsed}>
                {state.collapsed ? (
                  <MenuFoldOutlined style={{ fontSize: '22px' }}></MenuFoldOutlined>
                ) : (
                  <MenuUnfoldOutlined style={{ fontSize: '22px' }}></MenuUnfoldOutlined>
                )}
              </Button>
            )
          }}
        ></Header>
        <div class={'flex  mx-6 my-2'} style={{ height: 'calc(100vh - 80px)', overflowY: 'hidden' }}>
          <div
            class={(state.collapsed ? 'w-auto' : 'w-60') + ' max-w-60 bg-white mr-2 flex-shrink-0'}
            style={{ minHeight: 'calc(100vh - 80px)', display: menuDisplay.value }}
          >
            <Menu
              theme="light"
              mode="inline"
              onOpenChange={open}
              onSelect={select}
              openKeys={state.openKeys}
              selectedKeys={state.selectedKeys}
              inline-collapsed={state.collapsed}
            >
              <MenuItemList.value />
            </Menu>
          </div>
          <div class="flex-1 overflow-hidden">
            <div class="relative w-full h-full  pt-5">
              <div class={'absolute  top-3 text-xs2 font-bold'}>{barTitle.value}</div>
              <>{errorHappened.value ? renderErrorPage() : <RouterView></RouterView>}</>
            </div>
          </div>
        </div>
      </div>
    );
  }
});

MenuPage.displayName = 'MenuPage';

export default MenuPage;
